<script setup>
import { Plus, Upload } from '@element-plus/icons-vue'
import { ref } from 'vue'
import avatar from '@/assets/default.png'
const uploadRef = ref()

import useUserinfostore from '@/stores/userinfo'
const userinfostore = useUserinfostore();
//用户头像地址
const imgUrl = ref(userinfostore.info.userPic)
const imgDefaultUrl = ref(avatar)

import { useTokenStore } from '@/stores/token'
const tokenStore = useTokenStore()
const uploadsuccess = (result) => {
    imgUrl.value = result.data
}

import { updateUserAvatarService } from '@/api/user'
const updateAvatar = async () => {
    let result = await updateUserAvatarService(imgUrl.value)
    userinfostore.info.userPic = imgUrl.value
}


</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>更换头像</span>
            </div>
        </template>
        <el-row>
            <el-col :span="12">
                <el-upload ref="uploadRef" class="avatar-uploader" :show-file-list="false" :auto-upload="true"
                    action="/api/upload" name="file" :headers="{ 'Authorization': tokenStore.token }"
                    :on-success="uploadsuccess">
                    <img v-if="imgUrl" :src="imgUrl" class="avatar" />
                    <img v-else :src="imgDefaultUrl" width="278" />
                </el-upload>
                <br />
                <el-button type="primary" :icon="Plus" size="large"
                    @click="uploadRef.$el.querySelector('input').click()">
                    选择图片
                </el-button>
                <el-button type="success" :icon="Upload" size="large" @click="updateAvatar">
                    上传头像
                </el-button>
            </el-col>
        </el-row>
    </el-card>
</template>

<style lang="scss" scoped></style>